//
//  HQCDepartViewController.m
//  NursingManages
//
//  Created by Zhen Huang on 17/6/2.
//  Copyright © 2017年 huangzhen. All rights reserved.
//

#import "HQCDepartViewController.h"
#import "InitDbTable.h"
#import "TableHQCDept.h"
#import "TableEmployee.h"
#import "TablePubDictionaryItem.h"
#import "Model_Pub_Dictionary_Item.h"
@interface HQCDepartViewController ()
@property (nonatomic ,assign) NSInteger type;
@property (nonatomic ,strong) NSMutableArray *array;
@property (nonatomic ,strong) UIButton *dismissButton;
@end
@implementation HQCDepartViewController

- (instancetype)initWithType:(NSInteger )type
                  modelArray:(NSMutableArray *)modelArray
                 standard_id:(NSString *)standard_id
{
    if (self) {
        self.type = type;
        self.standard_id = standard_id;
        self.array = [NSMutableArray new];
    }
    return self;
}
-(NSMutableArray*) GetArrByFirstChar:(NSString*) firstChar{
    NSMutableArray* arr =[self.dataSourceFilterByFirstChar objectForKey:firstChar];
    return arr;
}

-(NSMutableArray*) GetArrBySectionNumber:(NSInteger) section {
    
    NSArray *sortArray = [self.dataSourceFilterByFirstChar.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    
    NSMutableArray* arr =[self.dataSourceFilterByFirstChar objectForKey:sortArray[section]];
    return arr;
}

- (NSArray *) escArray:(NSArray *)array{
    NSArray *sortArray = [array sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    return sortArray;
}


- (UITableView *)tableview
{
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0,  40, ScreenWidth, ScreenHeight  - 80 - NavBarHeight) style:UITableViewStylePlain];
        _tableview.tableFooterView = [[UIView alloc]init];
        [_tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        _tableview.delegate = self;
        _tableview.dataSource = self;
    }
    return _tableview;
}
- (UIButton *)dismissButton
{
    if (!_dismissButton) {
        _dismissButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_dismissButton setTitle:@"取消" forState:UIControlStateNormal];
        _dismissButton.backgroundColor = kNavBlueColor;
        _dismissButton.frame = CGRectMake(10, ScreenHeight - 40 - NavBarHeight, ScreenWidth - 20, 35);
        _dismissButton.layer.masksToBounds = YES;
        _dismissButton.layer.cornerRadius = 5;
        [_dismissButton addTarget:self action:@selector(dismiss:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _dismissButton;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.barTintColor = kNavBlueColor;
    self.navigationController.navigationBar.titleTextAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:18],NSForegroundColorAttributeName:[UIColor whiteColor]};
    [self refreshContactsData];
    self.mySearchBar =  [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
    if (self.type == 1) {
        self.mySearchBar.placeholder  = @"按科室名称搜索";
    }else {
        self.mySearchBar.placeholder  = @"按首字母搜索";
    }
    self.mySearchBar.delegate=self;
    if (self.type != 4) {
        [self.view addSubview:self.mySearchBar];
    }
    [self.view addSubview:self.tableview];
    [self.view addSubview:self.dismissButton];
}

#pragma mark 委托事件 UISearchBar

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchetxt
{
    self.dataSourceFilterByFirstChar = [NSMutableDictionary new];
    if (self.type == 1) {
        self.dataSource = [[[TableHQCDept alloc]init] GetHQCDeptArray:self.standard_id input_Code:searchetxt];
        [self DealDataSource];

    }else if (self.type == 2 || self.type == 3){
        self.dataSource = [[[TableEmployee alloc]init] GetEmpolyeeWithInputCode:searchetxt];
        [self DealDataSource];

    }else if(self.type == 5)
    {
        self.dataSource = [[[InitDbTable alloc]init]GetHSatisfcationDepartWithTypeID:self.standard_id input_Code:searchetxt];
        [self DealDataSource];
    }
    
    [self.tableview reloadData];
    
    if ( [ searchetxt isEqualToString: @"" ]){
        [self.mySearchBar resignFirstResponder];
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self.mySearchBar resignFirstResponder];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    [self.mySearchBar resignFirstResponder];
}

-(void)refreshContactsData{
    self.dataSourceFilterByFirstChar = [NSMutableDictionary new];
    if (self.type == 1) {
        self.dataSource = [[[TableHQCDept alloc]init] GetHQCDeptArray:self.standard_id input_Code:@""];

    }else if (self.type == 2 || self.type == 3){
        self.dataSource = [[[TableEmployee alloc]init] GetEmpolyee];
    }else if (self.type == 4){
        self.dataSource = [[[TablePubDictionaryItem alloc]init]getYechafangChafangShiduan];
    }else if (self.type == 5)
    {
        self.dataSource = [[[InitDbTable alloc]init]GetHSatisfcationDepartWithTypeID:self.standard_id];
    }
    [self DealDataSource];
}

- (void) DealDataSource {
    if (self.type == 1) {
        for (HQc_deptModel* model in self.dataSource) {
            CFStringTransform((CFMutableStringRef)model.DEPT_NAME, NULL, kCFStringTransformToLatin, false);
            CFStringTransform((CFMutableStringRef)model.DEPT_NAME, NULL, kCFStringTransformStripDiacritics, false);
            
            NSString* firstChar = [model.DEPART_ID substringToIndex:1];
            NSArray *array = [self escArray:self.dataSourceFilterByFirstChar.allKeys];
            if( [array containsObject: firstChar] ){
                NSMutableArray* arr =[self.dataSourceFilterByFirstChar objectForKey:firstChar];
                [arr addObject:model];
                [self.dataSourceFilterByFirstChar setObject:arr forKey:firstChar];
                
            }else{
                NSMutableArray* arr = [NSMutableArray new];
                [arr addObject:model];
                [self.dataSourceFilterByFirstChar setObject:arr forKey:firstChar];
                
            }
        }
 
    }else if (self.type == 2 || self.type == 3){
        for (Model_Pub_Employee* model in self.dataSource) {
            NSString* firstChar = [model.INPUT_CODE1 substringToIndex:1];
            NSArray *array = [self escArray:self.dataSourceFilterByFirstChar.allKeys];
            if( [array containsObject: firstChar] ){
                NSMutableArray* arr =[self.dataSourceFilterByFirstChar objectForKey:firstChar];
                [arr addObject:model];
                [self.dataSourceFilterByFirstChar setObject:arr forKey:firstChar];
                
            }else{
                NSMutableArray* arr = [NSMutableArray new];
                [arr addObject:model];
                [self.dataSourceFilterByFirstChar setObject:arr forKey:firstChar];
                
            }
        }

    }else if (self.type == 4){
        for (Model_Pub_Dictionary_Item* model in self.dataSource) {
            NSString* firstChar = [model.INPUT_CODE1 substringToIndex:1];
            NSArray *array = [self escArray:self.dataSourceFilterByFirstChar.allKeys];
            if( [array containsObject: firstChar] ){
                NSMutableArray* arr =[self.dataSourceFilterByFirstChar objectForKey:firstChar];
                [arr addObject:model];
                [self.dataSourceFilterByFirstChar setObject:arr forKey:firstChar];
                
            }else{
                NSMutableArray* arr = [NSMutableArray new];
                [arr addObject:model];
                [self.dataSourceFilterByFirstChar setObject:arr forKey:firstChar];
                
            }
        }
        
    }else if (self.type == 5)
    {
        for (Model_Hr_SatDept * model in self.dataSource) {
            CFStringTransform((CFMutableStringRef)model.DEPT_ID, NULL, kCFStringTransformToLatin, false);
            CFStringTransform((CFMutableStringRef)model.DEPT_ID, NULL, kCFStringTransformStripDiacritics, false);
            
            NSString* firstChar = [model.DEPT_NAME substringToIndex:1];
            NSArray *array = [self escArray:self.dataSourceFilterByFirstChar.allKeys];
            if( [array containsObject: firstChar] ){
                NSMutableArray* arr =[self.dataSourceFilterByFirstChar objectForKey:firstChar];
                [arr addObject:model];
                [self.dataSourceFilterByFirstChar setObject:arr forKey:firstChar];
                
            }else{
                NSMutableArray* arr = [NSMutableArray new];
                [arr addObject:model];
                [self.dataSourceFilterByFirstChar setObject:arr forKey:firstChar];
                
            }
        }

    }
}

-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    NSArray *array = [self escArray:[self.dataSourceFilterByFirstChar allKeys]];
    return array;
}

-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    return index;
}


- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSArray *array = [self escArray:[self.dataSourceFilterByFirstChar allKeys]];
    return array[section];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [self.dataSourceFilterByFirstChar allKeys].count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self GetArrBySectionNumber:section].count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"cell";
    UITableViewCell *cell = [self.tableview dequeueReusableCellWithIdentifier:cellID];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
    }
    
    NSArray *arresc = [self escArray:self.dataSourceFilterByFirstChar.allKeys];
    NSMutableArray* arr = [self.dataSourceFilterByFirstChar objectForKey:arresc[indexPath.section]];

    if (self.type == 1) {
        HQc_deptModel *model = arr[indexPath.row];
        [cell.textLabel setText:[NSString stringWithFormat:@"%@",model.DEPART_ID]];
    }else if (self.type == 2 || self.type == 3){
        Model_Pub_Employee *model = arr[indexPath.row];
        [cell.textLabel setText:[NSString stringWithFormat:@"%@(%@)",model.EMP_NAME,model.JUB_NUM]];
    }else if (self.type == 4){
        Model_Pub_Dictionary_Item *model = arr[indexPath.row];
        [cell.textLabel setText:[NSString stringWithFormat:@"%@",model.ITEM_NAME]];
    }else if (self.type == 5)
    {
        Model_Hr_SatDept *model = arr[indexPath.row];
        [cell.textLabel setText:[NSString stringWithFormat:@"%@",model.DEPT_NAME]];

    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSArray *arresc = [self escArray:self.dataSourceFilterByFirstChar.allKeys];
    NSMutableArray* arr = [self.dataSourceFilterByFirstChar objectForKey:arresc[indexPath.section]];
    if (self.type == 1) {
        HQc_deptModel *model = arr[indexPath.row];
        self.getBlocks(model.DEPT_NAME,model.DEPART_ID);

    }else if (self.type == 2) {
        Model_Pub_Employee *model = arr[indexPath.row];
        [self.array addObject:model];
        self.getBlock(self.array);
    }else if (self.type == 3)
    {
        Model_Pub_Employee *model = arr[indexPath.row];
        self.getBlock_nurse(model.EMP_NAME,model.EMP_ID);
    }else if (self.type == 4)
    {
        Model_Pub_Dictionary_Item *model = arr[indexPath.row];
        self.getBlock_Item(model.ITEM_ID,model.ITEM_NAME);
    }else if (self.type == 5)
    {
        Model_Hr_SatDept *dept_model = arr[indexPath.row];
        self.getBlocks_codeItem(dept_model.DEPT_NAME,dept_model.DEPT_ID);
    }
    else if (self.type == 6)
    {
        self.getBlock_nurse(@"1", @"2");
    }
    [self dismissViewControllerAnimated:YES completion:NULL];
}
- (void)dismiss:(UIButton *)sender
{
    [self dismissViewControllerAnimated:YES completion:NULL];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
